import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pin_code_fields/pin_code_fields.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/ShowDialog.dart';
import '../Order/WaybillDetails/FreightPaymentSuccessful.dart';
import '../TabBar/TabbarView.dart';
import '../http/api.dart';

class PayInsurancePremiums extends StatefulWidget {
  const PayInsurancePremiums({super.key, required this.goodsMap, required this.goodsType});
  final Map goodsMap;
  final int goodsType;
  @override
  State<PayInsurancePremiums> createState() => _PayInsurancePremiumsState();
}

class _PayInsurancePremiumsState extends State<PayInsurancePremiums> {
  int payType=-1;
  String insureStr="";


  void initState() {
    // TODO: implement initState
    super.initState();

    getInsureMoney();
  }
  @override
 Future<void>  getInsureMoney() async {
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(widget.goodsType==2?MyServiceUrl.header + 'api/goods/goods/pay/userEditGoodsPayAmount':
      MyServiceUrl.header + 'api/goods/goods/pay/userPayAmount',
      data: {
        "loadPlaceInfo":widget.goodsMap['loadPlaceInfo'],
        "unloadPlaceInfo":widget.goodsMap['unloadPlaceInfo'],
        "insurance":widget.goodsMap['insurance'],
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
        insureStr=jsonMap['data'];
        } else {

          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        title:Text( "支付保费",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        backgroundColor: Colors.white,
        centerTitle: true,
      ),
      body:Column(
        children: [
          Expanded(child: ListView(
            children: [

              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                padding: EdgeInsets.only(top: 22.h,bottom: 23.h),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Text("费用 ¥",style: TextStyle(color: Color.fromRGBO(228, 28, 35, 1),fontWeight: FontWeight.w600),),
                        Text(insureStr,style: TextStyle(color: Color.fromRGBO(228, 28, 35, 1),fontSize: 20.sp,fontWeight: FontWeight.w600),),
                      ],
                    ),

                    Container(
                      padding: EdgeInsets.all(10.h),
                      margin: EdgeInsets.only(top: 14.h),
                      width: screenSize.width-20.w,
                      height: 40.h,
                      color: Color.fromRGBO(251, 241, 233, 1),
                      child: Text("请选择支付方式",style: TextStyle(color: MyColors.themeColor),),
                    ),
                    SizedBox(height: 10.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/余额支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text("余额支付",style: TextStyle(color: Colors.black,),),
                                Text("可用"+"200.15"+"元",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                              ],
                            ),

                          ],
                        ),
                        IconButton(onPressed: (){
                          setState(() {
                            payType=1;
                          });
                        }, icon:payType==1?Icon(Icons.check_circle,color: MyColors.themeColor,):Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/微信支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Text("微信支付",style: TextStyle(color: Colors.black,),),
                          ],
                        ),
                        IconButton(onPressed: (){
                          setState(() {
                            payType=2;
                          });
                        }, icon:payType==2?Icon(Icons.check_circle,color: MyColors.themeColor,):Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/支付宝支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Text("支付宝支付",style: TextStyle(color: Colors.black,),),
                          ],
                        ),
                        IconButton(onPressed: (){
                          setState(() {
                            payType=3;
                          });
                        }, icon:payType==3?Icon(Icons.check_circle,color: MyColors.themeColor,):Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/银行卡支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Text("招商银行储蓄卡(9999)",style: TextStyle(color: Colors.black,),),
                          ],
                        ),
                        Row(
                          children: [
                            BrnTagCustom.buildBorderTag(
                              tagText: '支付立减6.9元',
                              textColor:Color.fromRGBO(246, 57, 13, 1),
                              borderColor: Color.fromRGBO(246, 57, 13, 1),
                              borderWidth: 1,
                              fontSize: 12.sp,
                            ),
                            IconButton(onPressed: (){
                              setState(() {
                                payType=4;
                              });
                            }, icon:payType==4?Icon(Icons.check_circle,color: MyColors.themeColor,): Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                          ],
                        ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    GestureDetector(
                      child:  Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("    "+"其他付款方式",style: TextStyle(color: Colors.black),),
                          Row(
                            children: [
                              Text("其他付款方式",style: TextStyle(color:MyColors.authTipColor),),
                              Icon(Icons.arrow_forward_ios,color: MyColors.authTipColor,size: 14,),
                              SizedBox(width: 10.w,),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

            ],
          ),
          ),
          Container(
            color: Colors.white,
            width: screenSize.width,
            height: 85.h,
            padding: EdgeInsets.only(top: 10.h,right: 15.w,left: 15.w,bottom: 40.h),
            child:BrnSmallMainButton(
              title: '立即支付¥'+insureStr,
              textColor: Colors.white,
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              bgColor: MyColors.themeColor,
              radius: 30,
              onTap: () {
                if(payType==-1){
                  BrnToast.show("请选择支付方式", context, duration: BrnDuration.short,);
                }else{
                  print(widget.goodsMap['insurance']);
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return EnterPasswordDialog(dataMap: widget.goodsMap, goodsType: widget.goodsType, );
                    },
                  );
                }


              },
            ),
          )
        ],
      ) ,
    );

  }
}

class EnterPasswordDialog extends StatefulWidget {
  const EnterPasswordDialog({super.key, required this.dataMap, required this.goodsType, });
  final Map dataMap;
  final int goodsType;
  @override
  State<EnterPasswordDialog> createState() => _EnterPasswordDialogState();
}

class _EnterPasswordDialogState extends State<EnterPasswordDialog> {
  TextEditingController _controller = TextEditingController();
  @override
  Map goodsSendMap={};
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    goodsSendMap=widget.dataMap;
  }
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Container(
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10))),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(),
                IconButton(
                  icon: Icon(Icons.close,color: MyColors.authTipColor,),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
              ],
            ),

            Text(
              '请输入支付密码',
              style: TextStyle(
                color:MyColors.textColor,
                fontSize: 16.sp,
                // fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: 16),
            Container(
              margin: EdgeInsets.only(left: 10.w,right:10.w),
              child: PinCodeTextField(

                  obscureText:false,
                  appContext: context,//context
                  length: 6,//输入的长度
                  controller: _controller,
                  autoFocus: true,
                  textStyle:TextStyle(color: Colors.black),
                  cursorColor: Colors.black,
                  pinTheme: PinTheme(
                    shape: PinCodeFieldShape.box, //输入框的形状
                    borderRadius: const BorderRadius.all(Radius.circular(0)),
                    activeColor:MyColors.themeColor,
                    selectedColor:MyColors.authTipColor,
                    inactiveColor:MyColors.backgreyColor,
                  ),

                  onChanged: (value)  async {


                    if(value.length==6) {
                      if(widget.goodsType==1){
                        goodsSendMap['payPassword']=value;
                        LoadingDialog.show(context);
                        dio.interceptors.add(InterceptorsWrapper(
                            onRequest: (options, handler) async {
                              options.headers["satoken"] =
                              await TokenManager.getToken();
                              return handler.next(options);
                            }
                        ));
                        dio.post(
                          MyServiceUrl.header +
                              'api/goods/goods/goods/add',
                          data: goodsSendMap,
                          options: Options(
                            sendTimeout: Duration(seconds: 2),
                            receiveTimeout: Duration(seconds: 50),
                          ),
                          onSendProgress: (a, b) =>
                              print('send ${a / b}'),
                          onReceiveProgress: (a, b) =>
                              print('received ${a / b}'),
                        )
                            .then((r) {
                          setState(() {
                            print(r);
                            Map<String, dynamic> jsonMap = json.decode(
                                r.toString());
                            // 获取code和data
                            String code = jsonMap['code'].toString();
                            if (code == "200") {
                              print("code：$code");
                              LoadingDialog.hide(context);
                              BrnDialogManager.showConfirmDialog(context,
                                  title: "发布成功,是否再发一单？",
                                  cancel: "",
                                  cancelWidget: GestureDetector(
                                    child: Center(
                                      child: Text("返回",
                                        style: TextStyle(
                                            color: Colors.black),),
                                    ),
                                    onTap: () {
                                      Navigator.pushReplacement(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) =>
                                              TabbarView(pateIndex: 0,),
                                          fullscreenDialog: true,),
                                      );
                                    },
                                  ),
                                  conformWidget: GestureDetector(
                                    child: Center(
                                      child: Text("再发一单",
                                        style: TextStyle(
                                            color: MyColors.themeColor),),
                                    ),
                                    onTap: () {
                                      Navigator.pop(context);
                                      Navigator.pop(context);
                                      Navigator.pop(context);
                                    },
                                  ),
                                  confirm: "",
                                  onConfirm: () {
                                    Navigator.pop(context);
                                  },
                                  onCancel: () {


                                  });
                            } else {
                              LoadingDialog.hide(context);
                              BrnToast.show(jsonMap['msg'], context);
                            }
                          });
                        }).catchError((error) {
                          print(error);
                          ;
                        });
                      }else{
                        goodsSendMap['payPassword']=value;
                        LoadingDialog.show(context);
                        dio.interceptors.add(InterceptorsWrapper(
                            onRequest: (options, handler) async {
                              options.headers["satoken"] =  await TokenManager.getToken();;
                              return handler.next(options);
                            }
                        ));
                        dio
                            .post(
                          MyServiceUrl.header+'api/goods/goods/goods/edit',
                          data: widget.dataMap,
                          options: Options(
                            sendTimeout: Duration(seconds: 2),
                            receiveTimeout: Duration(seconds: 50),
                          ),
                          onSendProgress: (a, b) =>
                              print('send ${a / b}'),
                          onReceiveProgress: (a, b) =>
                              print('received ${a / b}'),
                        )
                            .then((r) {
                          setState(() {
                            print(r);
                            Map<String, dynamic> jsonMap = json.decode(
                                r.toString());
                            // 获取code和data
                            String code = jsonMap['code'].toString();
                            if (code == "200") {
                              print("code：$code");
                              LoadingDialog.hide(context);
                              BrnToast.show("修改成功", context);
                              Navigator.pushReplacement(
                                context,
                                MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 0,),fullscreenDialog: true,),
                              );
                              // Navigator.pop(context);
                              // Navigator.pop(context);
                            }else{
                              LoadingDialog.hide(context);
                              BrnToast.show(jsonMap['msg'], context);
                            }
                          });
                        }).catchError((error) {
                          print(error);
                          ;
                        });
                      }

                    }

                  }
              ),
            ),

            SizedBox(height: 16),
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                // Navigator.push(context,
                //     MaterialPageRoute(builder: (context) {
                //       return PayAuthentication(
                //       );
                //     }));
              },
              child: Text('忘记密码？',
                style: TextStyle(
                  color: MyColors.themeColor,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
